package com.tuoyu.peopletest.view.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;


import com.tuoyu.peopletest.R;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 将布局管理器集成进来
 */
public class MyRecyclerView extends RecyclerView {

    private int spanCount;




    public MyRecyclerView(Context context) {
        this(context, null);
    }

    public MyRecyclerView(Context context,  AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyRecyclerView(Context context,  AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        //获取自定义值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable
                .MyRecyclerView, defStyle, 0);

        if (typedArray != null) {
            spanCount = typedArray.getInt(R.styleable.MyRecyclerView_spanCount, 0);



            typedArray.recycle();
        }
        setSpanCount(spanCount);
    }

    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);
    }

    public int getSpanCount() {
        return spanCount;
    }

    public void setSpanCount(int spanCount) {
        this.spanCount = spanCount;
        setLayoutManagerType();
    }

    private void setLayoutManagerType() {
        LayoutManager layoutManager = null;
        if (spanCount == 0) {
            //竖向滑动
            layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,
                    false);
        } else if (spanCount == 1) {
            //横向滑动
            layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL,
                    false);
        } else if (spanCount <= 10) {
            //
            layoutManager = new GridLayoutManager(getContext(), getSpanCount());

        } else if (spanCount > 10) {

            layoutManager = new GridLayoutManager(getContext(), getSpanCount() % 10,
                    GridLayoutManager.HORIZONTAL, false);
        }

        setLayoutManager(layoutManager);
        setItemAnimator(new DefaultItemAnimator());
    }


}
